package com.farm.wcp.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.farm.authority.FarmAuthorityService;
import com.farm.authority.service.UserServiceInter;
import com.farm.core.auth.domain.LoginUser;
import com.farm.core.page.ViewMode;
import com.farm.core.sql.query.DBRule;
import com.farm.core.sql.query.DBSort;
import com.farm.core.sql.query.DataQuery;
import com.farm.core.sql.query.DataQuerys;
import com.farm.core.sql.result.DataResult;
import com.farm.core.sql.result.ResultsHandle;
import com.farm.core.time.TimeTool;
import com.farm.project.domain.Company;
import com.farm.project.domain.Field;
import com.farm.project.domain.Project;
import com.farm.project.domain.ProjectFieldins;
import com.farm.project.domain.ProjectGradation;
import com.farm.project.domain.ProjectType;
import com.farm.project.domain.Task;
import com.farm.project.domain.TaskFile;
import com.farm.project.domain.TaskLog;
import com.farm.project.service.CompanyServiceInter;
import com.farm.project.service.ProjectFieldinsServiceInter;
import com.farm.project.service.ProjectGradationServiceInter;
import com.farm.project.service.ProjectServiceInter;
import com.farm.project.service.ProjectTypeServiceInter;
import com.farm.project.service.TaskServiceInter;
import com.farm.project.service.TaskTypeServiceInter;
import com.farm.wcp.util.ThemesUtil;
import com.farm.web.WebUtils;

/**
 * 任务统计分享
 * 
 * @author autoCode
 * 
 */
@RequestMapping("/taskQuery")
@Controller
public class TaskQueryWebController extends WebUtils {
	private static final Logger log = Logger.getLogger(TaskQueryWebController.class);
	@Resource
	private ProjectServiceInter projectServiceImpl;
	@Resource
	private ProjectTypeServiceInter projectTypeServiceImpl;
	@Resource
	private ProjectGradationServiceInter projectGradationServiceImpl;
	@Resource
	private TaskServiceInter taskServiceImpl;
	@Resource
	private TaskTypeServiceInter taskTypeServiceImpl;
	@Resource
	private ProjectFieldinsServiceInter projectFieldinsServiceImpl;
	@Resource
	private UserServiceInter userServiceImpl;
	@Resource
	private CompanyServiceInter companyServiceImpl;

	/***
	 * 选择查询周期
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/index")
	public ModelAndView userRound(HttpServletRequest request, HttpSession session) {
		ViewMode view = ViewMode.getInstance();
		try {
			return view.returnModelAndView("/web-simple/taskquery/index");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePage("error-sys"));
		}
	}

	/***
	 * 选择查询周期
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/loadReport")
	public ModelAndView loadReport(String projectname, String user, String companyname, String stime, String etime,
			Integer page, HttpServletRequest request, HttpSession session) {
		ViewMode view = ViewMode.getInstance();
		try {
			DataQuery query = taskServiceImpl.getTaskQuery(stime, etime);
			if (page == null) {
				page = 1;
			}
			query.setCurrentPage(page);
			if (StringUtils.isNotBlank(projectname)) {
				query.addRule(new DBRule("b.NAME", projectname, "like"));
			}
			query.addRule(new DBRule("g.userid", getCurrentUser(session).getId(), "="));
			if (StringUtils.isNotBlank(user)) {
				query.addRule(new DBRule("e.NAME", user, "like"));
			}
			if (StringUtils.isNotBlank(companyname)) {
				query.addRule(new DBRule("d.NAME", companyname, "like"));
			}
			query.setDistinct(true);
 
			// AND ((A.DOSTIME > '20210917000000' AND A.DOSTIME < '20210917999999') or
			// (F.ETIME > '20210917000000' AND F.ETIME < '20210917999999'))

			if (StringUtils.isNotBlank(stime) && StringUtils.isNotBlank(etime)) {
				stime = (stime.trim().replace("-", "") + "0000000000000000").substring(0, 14);
				etime = (etime.trim().replace("-", "") + "9999999999999999").substring(0, 14);
				query.addSqlRule("AND ((A.DOSTIME > '" + stime + "' AND A.DOSTIME < '" + etime + "') or (F.ETIME > '"
						+ stime + "' AND F.ETIME < '" + etime + "'))");
			}
			if (StringUtils.isNotBlank(stime) && StringUtils.isBlank(etime)) {
				stime = (stime.trim().replace("-", "") + "0000000000000000").substring(0, 14);
				query.addSqlRule("AND (A.DOSTIME > '" + stime + "'  or F.ETIME > '" + stime + "' )");
			}
			if (StringUtils.isBlank(stime) && StringUtils.isNotBlank(etime)) {
				etime = (etime.trim().replace("-", "") + "9999999999999999").substring(0, 14);
				query.addSqlRule("AND (A.DOSTIME < '" + etime + "'  or F.ETIME < '" + etime + "' )");
			}

			query.setPagesize(20);
			query.setDefaultSort(new DBSort("A.DOSTIME", "desc"));
			DataResult result = query.search();

			final String startTime = stime;
			final String endTime = etime;

			result.runHandle(new ResultsHandle() {
				@Override
				public void handle(Map<String, Object> row) {
					if (row.get("TASKID") != null) {
						List<TaskLog> logs = taskServiceImpl.getLogs((String) row.get("TASKID"));
						List<TaskLog> backlogs = new ArrayList<TaskLog>();
						for (TaskLog log : logs) {
							if (StringUtils.isNotBlank(startTime) && log.getEtime().compareTo(startTime) < 0) {
								continue;
							}
							if (StringUtils.isNotBlank(endTime) && log.getEtime().compareTo(endTime) > 0) {
								continue;
							}
							log.setText(taskServiceImpl.readText(log.getFileid()));
							backlogs.add(log);
						}
						row.put("LOGS", backlogs);
					}
				}
			});
			result.runformatTime("TASKETIME", "yyyy-MM-dd HH:mm");
			result.runformatTime("LOGTIME", "yyyy-MM-dd HH:mm");
			result.runformatTime("DOSTIME", "yyyy-MM-dd HH:mm");
			return view.putAttr("result", result).putAttr("datas", result.getResultList())
					.returnModelAndView("/web-simple/taskquery/commons/includeSearchReportloader");
		} catch (Exception e) {
			return ViewMode.getInstance().setError(e.getMessage(), e)
					.returnModelAndView(ThemesUtil.getThemePage("error-sys"));
		}
	}

}